//
//  BKLHealth_MCView.m
//  BKLMedicalCare
//
//  Created by ma c on 2017/6/14.
//  Copyright © 2017年 q mac. All rights reserved.
//

#import "BKLHealth_MCView.h"
#import "BKLHealth_MCCommon.h"
#import <Masonry.h>

#pragma mark - view 基类
#pragma maek -

@implementation BKLHealth_MCView

@end

#pragma mark - 导航视图
#pragma mark -

// 导航标题 标题 cell
@interface BKLHealth_MCNVCell : UICollectionViewCell
@property (nonatomic, strong)NSArray <NSNumber *>* defaultColors; // 4个数字 r g b a
@property (nonatomic, strong)NSArray <NSNumber *>* highLightColors;
- (void)fillData:(id)data;

// progress 0~1
- (void)willSelected:(CGFloat)progress;
- (void)willDeselected:(CGFloat)progress;
@end
@implementation BKLHealth_MCNVCell
{
    UILabel *_label;
    UIImageView *_bLine;
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    
//    _highLightColors = @[@(45/255.0), @(42/255.0), @(42/255.0), @(1)];
//    _defaultColors = @[@(204/255.0), @(204/255.0), @(204/255.0), @(1)];
    _defaultColors = @[@0, @0.7, @0.3, @1];
    _highLightColors = @[@0.4, @0, @0.6, @1];
    
    
    _label = [[UILabel alloc] init];
    _label.font = [UIFont systemFontOfSize:18];
    _label.textColor = [self colorWithArray:_defaultColors];
    _label.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_label];
    
    _bLine = [[UIImageView alloc] init];
    _bLine.backgroundColor = kBklHealth_bklYellow;
    [self.contentView addSubview:_bLine];
    
    [self makeConstraints];
}

- (void)makeConstraints {
    [_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
    }];
    
    [_bLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_label.mas_centerX);
        make.bottom.mas_equalTo(self.contentView.mas_bottom);
        make.height.mas_equalTo(2);
        make.width.mas_equalTo(40);
    }];
}

- (void)fillData:(id)data {
    if (!data) {
        return;
    }
    _label.text = data[@"source"][@"title"];
    NSIndexPath *indexPath = data[@"indexPath"];

    if (indexPath.row == 0) {
        _label.textColor = [self colorWithArray:_highLightColors];
        _bLine.alpha = 1;
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.contentView).offset(80);
        }];
    }
    else {
        _label.textColor = [self colorWithArray:_defaultColors];
        _bLine.alpha = 0;
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.contentView.mas_right).offset(-80);
        }];
    }
    
}
- (void)willDeselected:(CGFloat)progress {
    _label.textColor = [self gradientDefaultColor:progress];
    _bLine.alpha = 1 - progress;

}
- (void)willSelected:(CGFloat)progress {
    _label.textColor = [self gradientHighLightColor:progress];
    _bLine.alpha = progress;
    
}


// r g b a 数组转颜色
- (UIColor *)colorWithArray:(NSArray<NSNumber *>*)array {
    return [UIColor colorWithRed:[array[0] floatValue] green:[array[1] floatValue] blue:[array[2] floatValue] alpha:[array[3] floatValue]];
}

- (UIColor *)gradientDefaultColor:(CGFloat)percent{
    CGFloat r = self.defaultColors[0].floatValue + (1-ABS(percent))*(self.highLightColors[0].floatValue-self.defaultColors[0].floatValue);
    CGFloat g = self.defaultColors[1].floatValue + (1-ABS(percent))*(self.highLightColors[1].floatValue-self.defaultColors[1].floatValue);
    CGFloat b = self.defaultColors[2].floatValue + (1-ABS(percent))*(self.highLightColors[2].floatValue-self.defaultColors[2].floatValue);
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

- (UIColor *)gradientHighLightColor:(CGFloat)percent{
    CGFloat r = self.highLightColors[0].floatValue + (1-ABS(percent))*(self.defaultColors[0].floatValue-self.highLightColors[0].floatValue);
    CGFloat g = self.highLightColors[1].floatValue + (1-ABS(percent))*(self.defaultColors[1].floatValue-self.highLightColors[1].floatValue);
    CGFloat b = self.highLightColors[2].floatValue + (1-ABS(percent))*(self.defaultColors[2].floatValue-self.highLightColors[2].floatValue);
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}
@end

//导航视图
@interface BKLHealth_MCNavigatonView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@end
static NSString *const bkl_mcncCellIndetifier = @"bkl_mcncCellIndetifier";
@implementation BKLHealth_MCNavigatonView
{
    UICollectionView *_collectionView;
    NSIndexPath *_lastSelectIndexPath;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    CGRect viewFrame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64);
    self = [super initWithFrame:viewFrame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self initialize];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self scrollAtIndex:0];
            _lastSelectIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        });
    }
    return self;
}

- (void)initialize {
    
    _collectionView = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = [UIColor clearColor];
        [collectionView registerClass:[BKLHealth_MCNVCell class] forCellWithReuseIdentifier:bkl_mcncCellIndetifier];
        collectionView;
    });
    [self addSubview:_collectionView];

    [self makeConstraints];
}

- (void)makeConstraints {
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(20, 0, 0, 0));
    }];
}

- (NSArray *)dataSource {
    NSDictionary *source0 = @{@"title" : @"寻名医"};
    NSDictionary *source1 = @{@"title" : @"常见病症"};
    return @[source0, source1];
}

- (void)scrollAtIndex:(NSInteger)index {
    [_collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    [self collectionView:_collectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}

- (void)scrollDidScrll:(CGFloat)x {
    NSIndexPath *currentIndexPath = [_collectionView indexPathsForSelectedItems].firstObject;
    CGFloat pageWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat currentX = currentIndexPath.row * pageWidth;
    
    NSIndexPath *willSelectIndexPath;
    if (x > currentX) {
        willSelectIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row + 1 inSection:currentIndexPath.section];
    }
    else if (x < currentX) {
        willSelectIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row - 1 inSection:currentIndexPath.section];
    }
    BKLHealth_MCNVCell *currentCell = (BKLHealth_MCNVCell *)[_collectionView cellForItemAtIndexPath:currentIndexPath];
    [currentCell willDeselected:fabs(x - currentX) / pageWidth];
    
    BKLHealth_MCNVCell *willSelectCell = (BKLHealth_MCNVCell *)[_collectionView cellForItemAtIndexPath:willSelectIndexPath];
    [willSelectCell willSelected:fabs(x - currentX) / pageWidth];
    
}
#pragma mark - collection data source & delegate & delegate flow layout

// data source
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self dataSource].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BKLHealth_MCNVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bkl_mcncCellIndetifier forIndexPath:indexPath];
    return cell;
}

// delegate flow layout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.bounds.size.width / 2.0, collectionView.frame.size.height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

// delegate
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    BKLHealth_MCNVCell *bklCell = (BKLHealth_MCNVCell *)cell;
    NSDictionary *source = [[self dataSource] objectAtIndex:indexPath.row];
    NSDictionary *data = @{@"source" : source, @"indexPath" : indexPath};
    [bklCell fillData:data];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (![_lastSelectIndexPath isEqual:indexPath]) {
        if (self.deleagte && [self.deleagte respondsToSelector:@selector(navigationView:didSelect:)]) {
            [self.deleagte navigationView:self didSelect:indexPath.row];
        }
        _lastSelectIndexPath = indexPath;
    }
}

@end


#pragma mark - 预约体检view
#pragma mark -

@implementation BKLHealth_MCAppointmentOfMedicalView
{
    UIImageView *_bottomLine;
    UIImageView *_titleImgv;
    UILabel *_titleLab;
    UIImageView *_arrowImgv;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self initialize];
    }
    return self;
}

- (void)initialize {
    
    _bottomLine = [[UIImageView alloc] init];
    _bottomLine.backgroundColor = [kBklHealth_bklLightGray colorWithAlphaComponent:0.5];
    [self addSubview:_bottomLine];
    
    _titleImgv = [[UIImageView alloc] init];
    _titleImgv.layer.masksToBounds = YES;
    _titleImgv.layer.cornerRadius = 22;
    _titleImgv.image = [UIImage imageNamed:@"预约体检"];
    [self addSubview:_titleImgv];
    
    _titleLab = [[UILabel alloc] init];
    _titleLab.textColor = kBklHealth_bklBlack;
    _titleLab.font = [UIFont systemFontOfSize:16];
    _titleLab.text = @"预约体检";
    [self addSubview:_titleLab];
    
    _arrowImgv = [[UIImageView alloc] init];
    _arrowImgv.image = [UIImage imageNamed:@"arrowRight"];
    [self addSubview:_arrowImgv];
    
    [self makeConstraints];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchMe)];
    [self addGestureRecognizer:tap];
}

- (void)makeConstraints {
    
    [_bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(self);
        make.height.mas_equalTo(0.5);
    }];
    
    
    [_titleImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.mas_centerY);
        make.left.mas_equalTo(self.mas_left).mas_offset(12);
        make.height.with.mas_equalTo(44);
    }];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_titleImgv.mas_right).mas_offset(14);
        make.centerY.mas_equalTo(self.mas_centerY);
    }];
    
    [_arrowImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.mas_centerY);
        make.right.mas_equalTo(self.mas_right).offset(-10);
        make.width.mas_equalTo(10);
        make.height.mas_equalTo(14);
    }];
}

- (void)touchMe {
    if (self.deleagte && [self.deleagte respondsToSelector:@selector(appointmentOfMedicalViewDidSelected:)]) {
        [self.deleagte appointmentOfMedicalViewDidSelected:self];
    }
}

@end


#pragma mark - 多标题视图
#pragma mark -

@interface BKLHealth_MCMultipleTitlesView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@end

@implementation BKLHealth_MCMultipleTitlesView
{
    UICollectionView *_collectionView;
    NSIndexPath *_currentIndexPath;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    
    _currentIndexPath = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
    
    _collectionView = ({
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];;
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView;
    });
    [self addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    _collectionCellClassName = NSStringFromClass([UICollectionViewCell class]);
    _titleSource = [NSArray array];
    _leftSpacing = 10;
    _rightSpacing = 10;
    _lineSpacing = 30;
    _interitemSpacing = 30;
}

- (void)setCollectionCellClassName:(NSString *)collectionCellClassName {
    _collectionCellClassName = collectionCellClassName.copy;
    [_collectionView registerClass:[NSClassFromString(collectionCellClassName) class] forCellWithReuseIdentifier:[collectionCellClassName stringByAppendingString:@"Identifier"]];
}

- (void)selectedItemAtIndex:(NSInteger)index animated:(BOOL)animated {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    NSIndexPath *currentSelectedIndex = _currentIndexPath;
    if ([indexPath isEqual:currentSelectedIndex]) {
        return;
    }
    
    UICollectionViewCell *shouldDeselectedCell= [_collectionView cellForItemAtIndexPath:currentSelectedIndex];
    [_collectionView deselectItemAtIndexPath:currentSelectedIndex animated:animated];
    SEL didDeselected = NSSelectorFromString(@"didDeselected");
    if ([shouldDeselectedCell respondsToSelector:didDeselected]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [shouldDeselectedCell performSelector:didDeselected];
        #pragma clang diagnostic pop
    }
    
    UICollectionViewCell *shouSelectedCell = [_collectionView cellForItemAtIndexPath:indexPath];
    [_collectionView selectItemAtIndexPath:indexPath animated:animated scrollPosition:UICollectionViewScrollPositionCenteredHorizontally | UICollectionViewScrollPositionCenteredVertically];
    SEL didSelected = NSSelectorFromString(@"didSelected");
    if ([shouSelectedCell respondsToSelector:didSelected]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [shouSelectedCell performSelector:didSelected];
        #pragma clang diagnostic pop
    }
    _currentIndexPath = indexPath;
}

- (void)reloadData {
    [_collectionView reloadData];
}

#pragma mark - collection view delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _titleSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[_collectionCellClassName stringByAppendingString:@"Identifier"] forIndexPath:indexPath];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SEL fillData = NSSelectorFromString(@"fillData:");
    if ([cell respondsToSelector:fillData]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [cell performSelector:fillData withObject:_titleSource[indexPath.row]];
        #pragma clang diagnostic pop
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SEL computeSize = NSSelectorFromString(@"computeSize:");
    if ([NSClassFromString(_collectionCellClassName) respondsToSelector:computeSize]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        NSValue *sizeValue = [NSClassFromString(_collectionCellClassName) performSelector:computeSize withObject:_titleSource[indexPath.row]];
        #pragma clang diagnostic pop
        CGSize size = CGSizeMake([sizeValue CGSizeValue].width+1, CGRectGetHeight(collectionView.frame));
        return size;
    }
    
    if (CGSizeEqualToSize(CGSizeZero, _itemSize)) {
        return CGSizeMake(40, CGRectGetHeight(collectionView.frame));
    }
    return _itemSize;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, _leftSpacing, 0, _rightSpacing);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return _lineSpacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return _interitemSpacing;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.deleagte && [self.deleagte respondsToSelector:@selector(multipleTitlesView:didSelectedItemAtIndexPath:)]) {
        [self.deleagte multipleTitlesView:self didSelectedItemAtIndexPath:indexPath];
    }
    [self selectedItemAtIndex:indexPath.row animated:YES];
}


@end
